#! /bin/bash

# To show 95% confidence regions around a rotated finite rotation with its own confidence region
# Give command line args for chron_to_rotate chron_for_rotating_by directory_chron1 directory_chron2 rotation_direction  
clear

# Get started
echo "  "
echo "             -------------confregion_FP_ell--------------"
echo "  "
echo "  Add two finite rotations and convolve their confidence regions"
echo "  "

#make sure nothing's hiding under the bed
\rm -f temp temp2 temp2 ellipses.xy ell1.dat pole1.dat ell2.dat pole2.dat do_rotlist rotell_ellipse_temp.dat short_rotell.dat distaz.dat

unset -v CHRON1; unset -v CHRON2; unset -v DIREC1; unset -v DIREC2; unset -v FORWBACK

#sort out names of directories if given on the command line
FILESDIRECS1=`echo $1` # give "files" for files and "direct" for directories for pole 1
FILESDIRECS2=`echo $2` # give "files" for files and "direct" for directories for pole 2
DIREC1=`echo $3` # path to a directory (if "direct") or "dummy" (if "files") for pole 1
CHRON1=`echo $4` # chron label for the first pole
FORWBACK1=`echo $5` # "f" to use rotation angle forwards, "r" backwards, around pole 1
DIREC2=`echo $6` # path to a directory (if "direct") or "dummy" (if "files") for pole 2
CHRON2=`echo $7` # chron label for the second pole
FORWBACK2=`echo $8` # "f" to use rotation angle forwards, "r" backwards, around pole 2


echo "                    We're going to look for two rotations and their 95% confidence ellipses. "
echo "               The second rotation will be added to the first one - you choose whether the angle is forwards or backwards. "
echo "     Every rotation about a point on the periphery of the first ellipse will be added to every rotation about a point on the second ellipse. "
echo "                   The results are a summed rotation and an ellipse for the convolved uncertainty in its components.    "
echo " "
echo " "
echo "  Let's go! "



#FOR POLE 1 

#Find out whether we're finding and generating poles and ellipses from inversion directories, or giving filenames, for pole and ellipse 1
fd1=`echo $FILESDIRECS1 | awk '{if ($1=="files") print 0; else if ($1=="direct") print 1; else print 2}'`

if test "$fd1" = 0 ; then
    echo "Give path to a file with pole 1:"
    read polfil1
    echo "This is the rotation you just specified:"
    cat $polfil1
    echo "Is it listed as lon lat ang [lo] or lat lon ang [la]?"
    read lola
    cat $polfil1 | awk '{if (lola=="la") print $1,$2,$3; else print $2,$1,$3}' lola="$lola" > pole1.dat
    
    ANG=`cat pole1.dat | awk '{print $3}'`
    
	FRNUM=`echo $FORWBACK1 | awk '{if ($1=="f") print 1.0; else if ($1=="r") print -1.0}'`
	
#	echo "Give a chron label for this pole (e.g. C18y):"
#    read CHRON1

    echo "Give path to a file describing the ellipse around pole 1:"
    read ellfil1 
	ellfilpsxySE=`awk '{if (NR==1 && NF==5) print "1"; else if (NR==1 && NF!=5) print "0"}' $ellfil1`
    
    if test "$ellfilpsxySE" = 1 ; then
    echo "Your ellipse file was in \"psxy -SE\" format... reformatting to lon lat..."
    
	awk '{print $1,$2,"0.0000 0.0000",$4/111.2,$5/111.2,(($3*-1)+90)%360,CHRON1}' CHRON1="$CHRON1" $ellfil1 > temp
	calcell -Ctemp -V -S0.5 > temp2
# NB this call to calcell is simply to convert to an ellipse, no sigma value is needed. Instead, the 0.5 scales the output by half of the input (i.e. distance along semi-axes from centre to perimeter)	
	awk '{if (NR>1 && NR<362) print $1,$2,ANG*FRNUM}' ANG="$ANG" FRNUM="$FRNUM" temp2 > ell1.dat
    
    elif test "$ellfilpsxySE" = 0 ; then
    
    cat $ellfil1 | awk '{if ($1!=">") print $1,$2,ANG*FRNUM}' ANG="$ANG" FRNUM="$FRNUM" > ell1.dat
    
    fi

elif test "$fd1" = 1 ; then
  echo "You said that we should generate pole and ellipse 1 based on inversion results..."

  if [ -z "$DIREC1" ]; then
  echo "Give the path to the directory with the rotations and confidence region files for the first pole:"
  read DIREC1
  fi

  INVLIM=`cat $DIREC1/iter.dat | awk '{printf "%02d",$4-1}'`
  COUNTLIM=`echo $LISTLENGTH "1" | awk '{print $1-$2}' | head`

  #Need to make the ellipses file in case it doesn't exist or is old
  # This case is for 2D, use calcellsurf for 3D
  awk '{if ($3=="***********" || $4=="***********" || $5=="***********") NEXT; else print $0}' $DIREC1/confint_$INVLIM.dat > temp
calcell -Ctemp -V -S2.45 > temp2
# NB This call to calcell does need the appropriate sigma value.
  cp temp2 ellipses.xy 

  if [ -z "$CHRON1" ]; then
  	echo "For which chron is the pole you want to rotate?"
  	read CHRON1
  fi

  if [ -z "$FORWBACK1" ]; then
  echo "Do you want to apply the rotation with its angle forwards as calculated, or reversed (e.g for calculating a stage rotation)? [f/r]"
  read FORWBACK1
  fi

  ANG=`awk '{if ($4==CHRON1 && FORWBACK1=="f") print $3; else if ($4==CHRON1 && FORWBACK1=="r") print $3*-1}' CHRON1="$CHRON1" FORWBACK1="$FORWBACK1" $DIREC1/poles_$INVLIM.dat`

  #Isolate the ellipse for the rotation of interest
  line=`awk '{if ($2==CHRON1) print NR}' CHRON1="$CHRON1" ellipses.xy`

  awk '{if (NR<=line+360 && NR>line) print $1,$2,ANG}' ANG="$ANG" line="$line" ellipses.xy > ell1.dat

  #And isolate the pole at its centre

  awk '{if ($4==CHRON1) print $1,$2,ANG}' CHRON1="$CHRON1" ANG="$ANG" $DIREC1/poles_$INVLIM.dat > pole1.dat
else 
  echo "Start again - couldn't decipher how you wanted to get poles and ellipses: You gave $FILESDIRECS1 but your options were \"files\" or \"direct\""
fi 

echo "pole1.dat and ell1.dat written... moving on...."
echo ""
#******************************************************************************************************#
#NOW FOR POLE 2 

rm ellipses.xy

#Find out whether we're finding and generating poles and ellipses from inversion directories, or giving filenames, for pole and ellipse 2
fd1=`echo $FILESDIRECS2 | awk '{if ($1=="files") print 0; else if ($1=="direct") print 1; else print 2}'`

if test "$fd1" = 0 ; then
    echo "Give path to a file with pole 2:"
    read polfil2
    echo "This is the rotation you just specified:"
    cat $polfil2
    echo "Is it listed as lon lat ang [lo] or lat lon ang [la]?"
    read lola
    cat $polfil2 | awk '{if (lola=="la") print $1,$2,$3; else print $2,$1,$3}' lola="$lola" > pole2.dat
    
    ANG=`cat pole2.dat | awk '{print $3}'`

	FRNUM=`echo $FORWBACK2 | awk '{if ($1=="f") print 1.0; else if ($1=="r") print -1.0}'`
	
#	echo "Give a chron label for this pole (e.g. C18y):"
#    read CHRON2
    
    echo "Give path to a file describing the ellipse around pole 2:"
    read ellfil2 
	ellfilpsxySE=`awk '{if (NR==1 && NF==5) print "1"; else if (NR==1 && NF!=5) print "0"}' $ellfil2`
    
    if test "$ellfilpsxySE" = 1 ; then
    echo "Your ellipse file was in \"psxy -SE\" format... reformatting to lon lat..."
    
	awk '{print $1,$2,"0.0000 0.0000",$4/111.2,$5/111.2,(($3*-1)+90) % 360,CHRON2}' CHRON2="$CHRON2" $ellfil2 > temp
	calcell -Ctemp -V -S0.5 > temp2
# NB this call to calcell is simply to convert to an ellipse, no sigma value is needed. Instead, the 0.5 scales the output by half of the input (i.e. distance along semi-axes from centre to perimeter)	
	
	awk '{if (NR>1 && NR<362) print $1,$2,ANG*FRNUM}' ANG="$ANG" FRNUM="$FRNUM" temp2 > ell2.dat
    
    elif test "$ellfilpsxySE" = 0 ; then
    
    cat $ellfil2 | awk '{if ($1!=">") print $1,$2,ANG*FRNUM}' ANG="$ANG" FRNUM="$FRNUM" > ell2.dat
    
    fi
    
    

elif test "$fd1" = 1 ; then
  echo "You said that we should generate pole and ellipse 2 based on inversion results..."


  if [ -z "$DIREC2" ]; then
  echo "Give the path to the directory with the rotations and confidence region files for the second pole:"
  read DIREC2
  fi

  INVLIM=`cat $DIREC2/iter.dat | awk '{printf "%02d",$4-1}'`
  COUNTLIM=`echo $LISTLENGTH "1" | awk '{print $1-$2}' | head`

  #Need to make the ellipses file in case it doesn't exist or is old
  # This case is for 2D, use calcellsurf for 3D
  awk '{if ($3=="***********" || $4=="***********" || $5=="***********") NEXT; else print $0}' $DIREC2/confint_$INVLIM.dat > temp
  calcell -Ctemp -V -S2.45 > temp2
  #In this call to calcell we do need the appropriate sigma value for 2 degrees of freedom.
  cp temp2 ellipses.xy 

  if [ -z "$CHRON2" ]; then
	echo "For which chron is the rotation you want to use?"
	read CHRON2
  fi

  #Isolate the ellipse for the rotation
  line=`awk '{if ($2==CHRON2) print NR}' CHRON2="$CHRON2" ellipses.xy`
  #Fit it out with the rotation angle

  if [ -z "$FORWBACK2" ]; then
  echo "Do you want to apply the rotation with its angle forwards as calculated, or reversed? [f/r]"
  read FORWBACK2
  fi

  ANG=`awk '{if ($4==CHRON2 && FORWBACK2=="f") print $3; else if ($4==CHRON2 && FORWBACK2=="r") print $3*-1}' CHRON2="$CHRON2" FORWBACK2="$FORWBACK2" $DIREC2/poles_$INVLIM.dat`

  #echo $ANG

  awk '{if (NR<=line+360 && NR>line) print $1,$2,ANG}' ANG="$ANG" line="$line" ellipses.xy > ell2.dat

  #And isolate the pole at its centre

  awk '{if ($4==CHRON2) print $1,$2,ANG}' ANG="$ANG" CHRON2="$CHRON2" $DIREC2/poles_$INVLIM.dat > pole2.dat

else 
  echo "Start again - couldn't decipher how you wanted to get poles and ellipses: You gave $FILESDIRECS2 but your options were \"files\" or \"direct\""
fi 



# Now rotate pole 1 about pole 2

#v1: 
#poles_add_cmd `cat pole1.dat pole2.dat` > sumpole_$CHRON2"add"$CHRON1.dat

#v2: 
#pole1=`cat pole1.dat `
#pole2=`cat pole2.dat `
#poles_add_cmd $pole1 $pole2 > sumpole.dat

#v3:
./poles_add_cmd `cat pole1.dat pole2.dat | awk '{printf "%8.3f %8.3f %8.3f ", $1,$2,$3}'` > sumpole_$CHRON2"add"$CHRON1.dat

echo "Poles at centres of the ellipses added..."

# Read rotated pole coords into variables for distance calculation later
	PTLON_ROTPOL=`awk '{print $1}' sumpole_$CHRON2"add"$CHRON1.dat`
    PTLAT_ROTPOL=`awk '{print $2}' sumpole_$CHRON2"add"$CHRON1.dat`	

# Now add every rotation on the periphery of the ellipse of pole 1 to each of the 360 rotations on the ellipse about pole 2

echo "#! /bin/bash " > do_rotlist

i=1

while [ $i -le 360 ]
do 
printf "Now generating 360*360 rotation additions for the ellipses' peripheries... Done step $i of 360...                 \r"

ellrot1=`awk '{if (NR==i) print $2,$1,$3}' i="$i" ell1.dat` 

#awk '{print \"printf \"Done step 1 of 129600          \\r\"\; "poles_add_cmd ",ellrot1, $1,$2,$3,"}' ellrot1="$ellrot1" ell2.dat  >> do_rotlist
awk '{print "./poles_add_cmd ",ellrot1, $2,$1,$3,">> temp"}' ellrot1="$ellrot1" ell2.dat | awk '{print "printf \"Done rotation " ((i-1)*360)+(NR-1) " of 129600      \\r\" \;" , $0 }' i="$i" >> do_rotlist

i=$[$i+1]

done

echo "                                                                                                     "

rm temp
chmod 744 do_rotlist; ./do_rotlist; awk '{printf "%8.3f %8.3f\n", $1,$2}'  temp > rotell_ellipse_temp.dat
#do_rotlist > temp; awk '{printf "%8.3f %8.3f\n", $1,$2}'  temp > rotell_ellipse_temp.dat
#./do_rotlist; awk '{printf "%8.3f %8.3f\n", $1,$2}'  temp > rotell_ellipse_temp.dat


echo "Done the additions..."


#Cut out the repetitions
sort -u rotell_ellipse_temp.dat > short_rotell.dat

#Get azimuths and distances
awk '{print PTLON_ROTPOL,PTLAT_ROTPOL,$1,$2}' PTLON_ROTPOL="$PTLON_ROTPOL" PTLAT_ROTPOL="$PTLAT_ROTPOL" short_rotell.dat | calc_distaz.awk > distaz.dat
ell_az=`paste short_rotell.dat distaz.dat | sort -k 3 | tail -1 | awk '{print $4}'`
ell_az_calcell=`paste short_rotell.dat distaz.dat | sort -k3 | tail -1 | awk '{print (($4*-1)+90) % 360}'`
majax=`paste short_rotell.dat distaz.dat | sort -k 3 | tail -1 | awk '{print $3*2}'`
minax_az=`echo $ell_az | awk '{print $1+90}'`
minax=`paste short_rotell.dat distaz.dat | awk '{if ($4>minaz_ax) print $3}' minaz_ax="$minaz_ax" | head -1`


#Output suitable for psxy -SE
echo $PTLON_ROTPOL $PTLAT_ROTPOL $ell_az $majax $minax > rotell_psxySE_$CHRON2"add"$CHRON1.dat

#Output suitable for calcell

majaxdeg=`echo $majax | awk '{print $1/111.2}'`
minaxdeg=`echo $minax | awk '{print $1/111.2}'`

echo $PTLON_ROTPOL $PTLAT_ROTPOL "0.0000 0.0000" $majaxdeg $minaxdeg $ell_az_calcell $CHRON2"add"$CHRON1 > temp
calcell -Ctemp -V -S0.5 > temp2
awk '{if (NR>1 && NR<362) print $1,$2}' temp2 > rotell_plain_$CHRON2"add"$CHRON1.dat

#coarse test of success: does the summed-for pole lie inside the convolved ellipse? 

test1=`awk '{print $1,$2}' sumpole_$CHRON2"add"$CHRON1.dat`
test2=`awk '{print $1,$2}' sumpole_$CHRON2"add"$CHRON1.dat | gmtselect -Frotell_plain_$CHRON2"add"$CHRON1.dat`
echo $test1 $test2 | awk '{if ($1==$3 && $2==$4) print "Positive test! The summed pole lies within the combined ellipse!"; else print "Negative test! The summed pole is not inside the ellipse!! Good luck finding the misteak!!!"}'
outputs=`echo $test1 $test2 | awk '{if ($1==$3 && $2==$4) print "1"; else print "0"}'`

if test "$outputs" = 1 ; then
echo ""


echo "Written convolved ellipse for $CHRON1 added to $CHRON2, suitable for psxy -SE, and as plain coordinates suitable for psxy or further rotation. Thangyew."
echo ""
echo "-------------------------------------------------------------------------------------"
echo "                                  OUTPUTS: "
echo "The files written are: " rotell_psxySE_$CHRON2"add"$CHRON1.dat " - the ellipse, for plotting with psxy -SE "
echo "                       " rotell_plain_$CHRON2"add"$CHRON1.dat "- the ellipse, for plotting with psxy or further use with this script, and"
echo "                       " sumpole_$CHRON2"add"$CHRON1.dat "			   - the best fitting rotation at the centre of the ellipse."
echo "-------------------------------------------------------------------------------------"

fi

#put the toys away
#\rm -f temp temp2 temp2 ellipses.xy ell1.dat pole1.dat ell2.dat pole2.dat do_rotlist rotell_ellipse_temp.dat short_rotell.dat distaz.dat
